package usersManagement.controller;

import org.slf4j.Logger;
import usersManagement.model.Shipment;
import usersManagement.model.User;
import usersManagement.security.LoggedUser;
import usersManagement.service.ShipmentService;
import usersManagement.util.AppLog;

import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.Produces;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;
import java.util.List;

@Named("shipments")
@SessionScoped
public class ShipmentController implements Serializable {
    private static final long serialVersionUID = -5159985234541085776L;
// ------------------------------ FIELDS ------------------------------

    List<Shipment> shipmentsList ;

    @Inject @AppLog private Logger log; // all implementations are serializable, the interface is not, so the warning can be ignored

    @Inject
    private FacesContext facesContext;

    @Inject
    private ShipmentService shipmentService ;

    private Shipment selectedShipment ;

    @Inject private Event<Shipment> shipmentEvent;

    // --------------------------- INITIALIZATION ---------------------------

    @PostConstruct
    public void init() {
        shipmentsList = shipmentService.findAvailableShipments() ;
    }

    @Produces
    @Named
    public List<Shipment> getShipmentsList() {

        return shipmentsList;
    }

    public void onShipmentListChanged(@Observes final Shipment shipment) {
        log.debug("Refresh shipments list");
        shipmentsList = shipmentService.findAvailableShipments() ;
    }

    public void setShipmentsList(List<Shipment> shipmentsList) {

        this.shipmentsList = shipmentsList;
    }

    public Shipment getSelectedShipment() {
        return selectedShipment;
    }

    public void setSelectedShipment(Shipment selectedShipment) {
        this.selectedShipment = selectedShipment;
    }

    public void takeOwnership() {

        if ( selectedShipment != null )
            shipmentService.assignOwnershipToLoggedUser(selectedShipment);
        else
            log.warn("Shipment is null");

        shipmentEvent.fire(selectedShipment);
    }
}
